<?php

declare(strict_types=1);

namespace App\Task;

use App\Model\Aftersale;
use App\Model\AftersaleSet;
use App\Model\FlyOrder;
use App\Service\AftersaleService;
use App\Service\AftersaleSetService;
use App\Service\FlyOrderService;
use App\Service\PayService;
use App\Service\ShopOrderService;
use Hyperf\Crontab\Annotation\Crontab;

/**
 * 售后但超过时限自动处理
 * Class AfOuterTimeTask
 * @package App\Task
 */
class AfOuterTimeTask
{

    public function execute(): void
    {
        $af_sets = AftersaleSet::whereIn('time_type', [1, 2, 3])->pluck('days', 'time_type');
        $af_sets_arr = empty($af_sets) ? [] : $af_sets->toArray();
        $af_fields = ['af_id', 'af_status', 'user_id', 'af_sn', 'af_type', 'order_id', 'apply_time', 'check_time', 'user_response_time', 'is_refund', 'refund_time', 'check_time', ''];
        $af_list = Aftersale::query()
            ->with(['with_order'])
            ->where('af_order_style', '=', 1) // 仅限电商商品售后期限判断
            ->whereIn('af_status', [AftersaleService::STATUS_WAIT_CHECK, AftersaleService::STATUS_CHECKED])->select($af_fields)->get();
        $shop_check_duration = $af_sets_arr[1] ?? 0;//售后处理时限 超时自动同意
        $user_response_duration = $af_sets_arr[2] ?? 0;// 用户回传单号时限 超时售后单关闭
        $refund_response_duration = $af_sets_arr[3] ?? 0;// 自动退款时限 超时自动退款

        $order = new FlyOrderService();
        $af = new AftersaleService();
        $shop_order = new ShopOrderService();
        if (!empty($af_list)) {
            $afService = (new AftersaleService());
            foreach ($af_list->toArray() as $item) {
                // 售后处理时限 - 超过时限自动审核通过
                if ($item['af_status'] == AftersaleService::STATUS_WAIT_CHECK) {
                    if (time() > $shop_check_duration * 86400 + $item['apply_time']) {
                        $with_order = $shop_order->getOrderDetails($item['order_id'], $item['shop_id']);
                        // 如果为手动送回时限-自动退款
                        if (in_array($item['af_type'], [1, 2]) && $with_order['delivery_type'] != 1) {
                            // 直接退款
                            $shop_order->afRefund($item['shop_id'], $item['af_sn'], $item['is_back_coupon'], $item['is_back_delivery']);
                            // 订单全退关闭订单
                            $order_details = $order->getDetails($item['user_id'], $item['order_id']);
                            $order_data = [
                                'curr_af_id' => $item['af_id']
                            ];
                            // 当前售后完成-直接退款 - 当前直接退判断全部退
                            if ($item['af_status'] == AftersaleService::STATUS_FINISHED && $af->getSuccessBackNum($item['order_id']) == array_sum(array_column($order_details['with_products'], 'quantity'))) {
                                $order_data['order_status'] = FlyOrderService::STATUS_CLOSED;
                            }
                            FlyOrder::where(['order_id' => $item['order_id']])->update($order_data);
                        }
                        Aftersale::where(['af_id' => $item['af_id']])->update([
                            'af_status' => AftersaleService::STATUS_CHECKED,
                            'check_time' => time(),// 审核时间
                        ]);
                    }
                } else {
                    // 已审核 - 待回传单号（超时关闭售后单）
                    if (in_array($item['af_type'], [AftersaleService::TYPE_REFUND_P, AftersaleService::TYPE_SWAP, AftersaleService::TYPE_REPAIR])) {
                        if (empty($item['user_response_time']) && time() > $user_response_duration * 86400 + $item['apply_time']) {
                            // 超时未回传单号，自动取消
                            $afService->afCancel($item['user_id'], $item['af_sn'], 1);
                        }
                    } else {
                        // 退货退款 已审核-超过退款时限（自动退款）
                        if ($item['af_status'] == AftersaleService::STATUS_CHECKED && $item['af_type'] == 2 && $item['is_refund'] == 0) {
                            if (!empty($item['user_response_time']) && time() > $refund_response_duration * 86400 + $item['user_response_time']) {
                                // 超时自动退款
                                if (!empty($item['refund_price']) && $item['refund_price'] < $item['with_order']['paid_price']) {
                                    $shop_order->afRefund($item['shop_id'], $item['af_sn'], $item['is_back_coupon'], $item['is_back_delivery']);
                                    // 订单全退关闭订单
                                    $order_details = $order->getDetails($item['user_id'], $item['order_id']);
                                    $order_data = [
                                        'curr_af_id' => $item['af_id']
                                    ];
                                    // 当前售后完成-直接退款 - 当前直接退判断全部退
                                    if ($item['af_status'] == AftersaleService::STATUS_FINISHED && $af->getSuccessBackNum($item['order_id']) == array_sum(array_column($order_details['with_products'], 'quantity'))) {
                                        $order_data['order_status'] = FlyOrderService::STATUS_CLOSED;
                                    }
                                    FlyOrder::where(['order_id' => $item['order_id']])->update($order_data);
                                }
                            }
                        }
                    }
                }
            }
        }
    }

}